<?php namespace App\Core\Service\Services;

use DB;
use App\Core\Exceptions\InputError;

trait Creater{
    
    public $createFields = [];
    public $createData = [];
    public $createModel;

    public function create(){
        try {
            $this->fireEvent('createGeneratingFeilds');
            //获取字段
            $this->createGenerateFeilds();
            $this->fireEvent('createGeneratedFeilds');
            //填充数据
            $this->createGenerateData();
            $this->fireEvent('createGeneratedData');
            //数据验证
            $this->createValidate();
            if(!$this->validateRes['status']){
                $error = array_shift($this->validateRes['errors']);
                return $this->inputError('数据格式有误。字段'.$error[0].$error[1]);
            }
            //保存数据
            $this->fireEvent('createBeforeSave');
            $this->createSaveData();
            $this->fireEvent('createAfterSave');
            return $this->success();
		} catch (\Exception $ex) {
            if($ex instanceof InputError){
                return $this->inputError($ex->getMessage());
            }
			return $this->sysError($ex);
		}
    }

    //获取创建字段
    protected function createGenerateFeilds(){
        $this->createFields = $this->getMeta()->getCreateFields();
    }
    
    //根绝所给字段填充数据
    protected function createGenerateData(){
        $this->createData = $this->getMeta()->getData($this->createFields);
    }
    
    //验证数据
    protected function createValidate(){
        $rules = $this->getMeta()->getRules($this->createFields);
        $this->validateRes = $this->validator->validate($this->createData, $rules);
    }
    
    //保存数据
    protected function createSaveData(){
        DB::beginTransaction();
        try {
            $this->fireEvent('createSaving');
            $this->createModel = $this->getRepository()->create($this->createData);
            $this->fireEvent('createSaved');
            DB::commit();
		} catch (\Exception $ex) {
            DB::rollBack();
			throw $ex;
        }
    }
}